package com.egg.basic.util;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.egg.basic.config.aliyun.AliyunOSSConfig;
import com.egg.common.core.constant.StringPool;
import com.egg.common.util.IdGenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;

/**
 * 文件阿里云 工具类
 *
 * @author east
 */
@Slf4j
public class FileAliyunUtil {


    private static OSS client;

    public void setOSS(OSS init) {
        client = init;
    }


    /**
     * 上传文件
     */
    public static String upload(MultipartFile multipartFile) {
        // 判断文件是否为空
        if (null == multipartFile) {
            return "";
        }
        String suffix = getSuffix(multipartFile);
        String directory = getDirectory(multipartFile);
        String fileName = DateUtil.today() + StringPool.SLASH + IdGenUtil.strId() + suffix;
        String filePath = directory + StringPool.SLASH + fileName;
        try {
            PutObjectResult result = client.putObject(AliyunOSSConfig.bucketName(), filePath, multipartFile.getInputStream());
            if (null == result) {
                return "";
            }
        } catch (Exception e) {
            log.error("上传文件失败 ", e);
            return "";
        }
        return getUrl(filePath);
    }

    /**
     * 获取目录
     *
     * @param multipartFile
     * @return
     */
    private static String getDirectory(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        String directory = "others";
        if (null == fileName) {
            return directory;
        }
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
            directory = "images";
        } else if (fileName.endsWith(".mp4")) {
            directory = "videos";
        }
        return directory;
    }

    /**
     * 获取后缀
     *
     * @param multipartFile
     * @return
     */
    private static String getSuffix(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        if (null == originalFilename) {
            return "";
        }
        return originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    /**
     * 访问地址
     *
     * @param filePath
     * @return
     */
    private static String getUrl(String filePath) {
        if (null == filePath) {
            return "";
        }
        URL url = client.generatePresignedUrl(AliyunOSSConfig.bucketName(), filePath, DateUtil.date());
        return url.getProtocol() + "://" + url.getHost() + url.getPath();
    }


}